package com.example.qiaoruian.shequ.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.qiaoruian.shequ.CuxiaoActivity;
import com.example.qiaoruian.shequ.MessageActivity;
import com.example.qiaoruian.shequ.R;
import com.example.qiaoruian.shequ.ShequInfoActivity;
import com.example.qiaoruian.shequ.ShequManangerActivity;
import com.example.qiaoruian.shequ.adapter.ListViewAdapter;
import com.example.qiaoruian.shequ.bean.TodayWeather;
import com.example.qiaoruian.shequ.bean.UserBean;
import com.example.qiaoruian.shequ.contant.LocalCity;
import com.example.qiaoruian.shequ.contant.TargetUrl;
import com.example.qiaoruian.shequ.view.BaseFragment;
import com.example.qiaoruian.shequ.view.MyTitle;
import com.example.qiaoruian.shequ.view.SettingWeatherItemView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.example.qiaoruian.shequ.utils.WeatherUtil.parseXML;

/**
 * Created by qiaoruian on 2017/5/8.
 */

public class HomeFragment extends BaseFragment {
    private MyTitle mTitle;
    private SettingWeatherItemView item_home;
    private GridView gv_item;
    private ListView item_lv;
    private List<UserBean> list;
    private LinearLayout ll_guanweihui;
    private LinearLayout list_fragment;
    private static HomeFragment tupian = null;
    private LocationClient mLocationClient;
    private MyLocationListener myLocationListener;
    private static String cityName = "";
    private String result = "";
    private Bitmap bitmap1, bitmap2;
    public static int tupian_hour = 60;
    private String City;
    private String cityID;
    private TodayWeather todayWeather;

    @Override
    protected void initData() {
        list = new ArrayList<>();
    }

    @Override
    protected void initViewData(View v) {
        mTitle = (MyTitle) v.findViewById(R.id.mtitle);

        list_fragment = (LinearLayout) v.findViewById(R.id.list_fragment);
        ll_guanweihui = (LinearLayout) v.findViewById(R.id.ll_guanweihui);
        mTitle.getIv_item().setVisibility(View.VISIBLE);
        mTitle.getIv_item2().setVisibility(View.GONE);
        list_fragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CuxiaoActivity.class);
                startActivity(intent);
            }
        });
        mTitle.getTv_title().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ShequInfoActivity.class);
                startActivity(intent);
            }
        });

        ll_guanweihui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ShequManangerActivity.class);
                startActivity(intent);
            }
        });
        item_home = (SettingWeatherItemView) v.findViewById(R.id.item_home);

        item_lv = (ListView) v.findViewById(R.id.lv_ll);
//        gv_item = (GridView)v.findViewById(R.id.gv_item);
        getData();
        item_lv.setAdapter(new ListViewAdapter(getData(), getContext()));
        setListViewHeightBasedOnChildren(item_lv);
        item_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), MessageActivity.class);
                startActivity(intent);
            }
        });
        mLocationClient = new LocationClient(getActivity());
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
//        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
    }

    class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            cityName = bdLocation.getCity();
            send(cityName);
            Log.d("Locate", cityName);

        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }

    private void send(String city) {
        if (city.contains("市") || city.contains("省")) {
            City = city.substring(0, city.length() - 1);
        }
        cityID = LocalCity.getCityIdByName(City);
        final String target = TargetUrl.url1 + cityID;  //要提交的目标地址
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection urlConnection = null;
                try {
                    URL url = new URL(target);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(8000);
                    urlConnection.setReadTimeout(8000);
                    InputStream in = urlConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer sb = new StringBuffer();
                    String str;
                    while ((str = reader.readLine()) != null) {
                        sb.append(str);
                        Log.d("date from url", str);
                    }
                    String response = sb.toString();
                    Log.d("response", response);
                    in.close();
                    reader.close();
                    todayWeather = parseXML(response);
                    if (todayWeather != null) {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = todayWeather;
                        mhandler.sendMessage(message);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    private Handler mhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    updateTodayWeather((TodayWeather) msg.obj);
                    item_home.setTodayWeather((TodayWeather) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public List<UserBean> getData() {
        List<UserBean> l = new ArrayList<>();
        l.add(new UserBean(1, "停电通知", "本小区将于2017年2月13日08:00-15:00时间段于全体社区用户注意，提前做好相关预防措施！并配合有关检查工作。\\n\\n 公共电梯及公共照明！将启用发电机发电保持运行状态，若有不便之处敬请见谅！"));
        l.add(new UserBean(2, "停电通知", "本小区将于2017年2月13日08:00-15:00时间段于全体社区用户注意，提前做好相关预防措施！并配合有关检查工作。\\n\\n 公共电梯及公共照明！将启用发电机发电保持运行状态，若有不便之处敬请见谅！"));
        l.add(new UserBean(1, "停电通知", "本小区将于2017年2月13日08:00-15:00时间段于全体社区用户注意，提前做好相关预防措施！并配合有关检查工作。\\n\\n 公共电梯及公共照明！将启用发电机发电保持运行状态，若有不便之处敬请见谅！"));
        l.add(new UserBean(2, "停电通知", "本小区将于2017年2月13日08:00-15:00时间段于全体社区用户注意，提前做好相关预防措施！并配合有关检查工作。\\n\\n 公共电梯及公共照明！将启用发电机发电保持运行状态，若有不便之处敬请见谅！"));
        return l;
    }

    void updateTodayWeather(TodayWeather todayWeather) {
        item_home.getTv_city().setText(todayWeather.getCity());

//        humidityT.setText("湿度:" + todayWeather.getShidu());
        item_home.getTv_pm2_5().setText(todayWeather.getPm25());
        item_home.getTv_airstate().setText(todayWeather.getQuality());
//        weekT.setText(todayWeather.getDate());
        item_home.getTv_wendu().setText(todayWeather.getWendu() + "℃");
        item_home.getTv_weather().setText(todayWeather.getType());


//        if (todayWeather.getPm25() != null) {
//            int pm25 = Integer.parseInt(todayWeather.getPm25());
//            if (pm25 <= 50) {
//                PM25Img.setImageResource(R.drawable.biz_plugin_weather_0_50);
//            } else if (pm25 >= 51 && pm25 <= 100) {
//                PM25Img.setImageResource(R.drawable.biz_plugin_weather_51_100);
//            } else if (pm25 >= 101 && pm25 <= 150) {
//                PM25Img.setImageResource(R.drawable.biz_plugin_weather_101_150);
//            } else if (pm25 >= 151 && pm25 <= 200) {
//                PM25Img.setImageResource(R.drawable.biz_plugin_weather_151_200);
//            } else if (pm25 >= 201 && pm25 <= 300) {
//                PM25Img.setImageResource(R.drawable.biz_plugin_weather_201_300);
//            }
//        }
//        if (todayWeather.getType() != null) {
//            Log.d("type", todayWeather.getType());
//            switch (todayWeather.getType()) {
//                case "晴":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_qing);
//                    break;
//                case "阴":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_yin);
//                    break;
//                case "雾":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_wu);
//                    break;
//                case "多云":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_duoyun);
//                    break;
//                case "小雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_xiaoyu);
//                    break;
//                case "中雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_zhongyu);
//                    break;
//                case "大雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_dayu);
//                    break;
//                case "阵雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_zhenyu);
//                    break;
//                case "雷阵雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_leizhenyu);
//                    break;
//                case "雷阵雨加暴":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_leizhenyubingbao);
//                    break;
//                case "暴雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_baoyu);
//                    break;
//                case "大暴雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_dabaoyu);
//                    break;
//                case "特大暴雨":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_tedabaoyu);
//                    break;
//                case "阵雪":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_zhenxue);
//                    break;
//                case "暴雪":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_baoxue);
//                    break;
//                case "大雪":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_daxue);
//                    break;
//                case "小雪":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_xiaoxue);
//                    break;
//                case "雨夹雪":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_yujiaxue);
//                    break;
//                case "中雪":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_zhongxue);
//                    break;
//                case "沙尘暴":
//                    weatherImg.setImageResource(R.drawable.biz_plugin_weather_shachenbao);
//                    break;
//                default:
//                    break;
//            }
//        }
        Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT).show();
    }
}
